package com.lovo.stock.controller;

import com.lovo.stock.bean.UserBean;
import com.lovo.stock.constant.MessageCode;
import com.lovo.stock.service.IJournalService;
import com.lovo.stock.service.IUserService;
import com.lovo.stock.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    IUserService userService;
    @Autowired
    IJournalService journalService;
    /**
     * 用户登录
     * @param userBean
     * @return
     */
    @RequestMapping("/userLogin")
    @Transactional
    public ResponseResult<UserBean> userLogin(HttpServletRequest request, UserBean userBean){
        ResponseResult<UserBean> responseResult=new ResponseResult<>();
        try {
            //查询数据库中中角色
            UserBean user=userService.queryUser(userBean);
            //用户名，密码正确
            if (user!=null){
                //查询出其权限值
                user=userService.queryUserById(user.getUserId());
                //将其存入session中
                request.getSession().setAttribute("user",user);
                responseResult.setData(user);
                //记录在日志
                journalService.addJournal("登录了系统",user);
                return responseResult;
            }
            //用户名或密码错误
            responseResult.setMessage(MessageCode.ACCOUNT_OR_PASSWORD_ERROR.message);
            responseResult.setCode(MessageCode.ACCOUNT_OR_PASSWORD_ERROR.code);
            return responseResult;
        }catch (Exception e){
            e.printStackTrace();
            responseResult.setMessage(MessageCode.ERROR.message);
            responseResult.setCode(MessageCode.ERROR.code);
            return responseResult;
        }
    }

}
